package org.budo.support.image;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;

import javax.imageio.ImageIO;

import org.budo.support.http.client.HttpUtil;
import org.budo.support.http.client.Response;
import org.budo.support.javax.imageio.util.ImageIoUtil;
import org.budo.support.lang.util.IoUtil;
import org.budo.support.lang.util.NumberUtil;
import org.budo.support.lang.util.RandomUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class ImageUtil {
    /**
     * 截取图片
     */
    public static void cutPic(BufferedImage fromImage, int startX, int startY, int width, int height, File to) {
        try {
            int endX = (int) (width * 0.55);
            int endY = (int) (height * 0.85);

            BufferedImage toImage = new BufferedImage(endX - startX, endY - startY, 4);

            for (int x = startX; x < endX; ++x) {
                for (int y = startY; y < endY; ++y) {
                    int rgb = fromImage.getRGB(x, y);
                    toImage.setRGB(x - startX, y - startY, rgb);
                }
            }

            FileOutputStream fileOutputStream = IoUtil.fileOutputStream(to);
            ImageIO.write(toImage, "png", fileOutputStream);
            fileOutputStream.close();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    public static BufferedImage randomImage(Integer width, Integer height) {
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D graphics2d = bufferedImage.createGraphics();

        int r = RandomUtil.randomInt(0, 255);
        int g = RandomUtil.randomInt(0, 255);
        int b = RandomUtil.randomInt(0, 255);

        graphics2d.setColor(new Color(r, g, b));
        graphics2d.fillRect(0, 0, width, height);

        graphics2d.dispose();
        return bufferedImage;
    }

    public static Image urlToImage(String url) {
        Response response = HttpUtil.get(url);
        for (int i = 0; i < 10; i++) { // 最多10次跳转
            if (!NumberUtil.equals(302, response.getStatus())) { // 不是跳转
                break; // 出去
            }

            String location = response.getHeader("Location");
            response = HttpUtil.get(location);
        }

        byte[] bytes = response.getResponseData();
        if (null == bytes) {
            log.error("#70 bytes=" + bytes + ", url=" + url);
            return null;
        }

        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        return ImageIoUtil.read(inputStream);
    }
}
